package system

import (
	"errors"
	"fmt"
	"k8s-admin/global"
	"k8s-admin/models"
	"k8s-admin/utils"
)

type InterfaceServices interface {
	CreateService(username, password, authkey, ipaddress, ServiceName, ServiceVersion string, status, port int) error
	List() (*models.ListReq, error)
	Delete(propertynumber string) error
	UpdateService(property_number, username, password, authkey, ipaddress, ServiceName, ServiceVersion string, status, port int) error
}

type servicesInfo struct {
}

func NewServicesInterface() InterfaceServices {
	return &servicesInfo{}
}

func (r *servicesInfo) CreateService(username, password, authkey, ipaddress, ServiceName, ServiceVersion string, status, port int) error {
	propertynumber := utils.GemSnowFlask(ServiceName)
	service := models.Service{
		Username:       username,
		Password:       password,
		AuthKey:        authkey,
		IPAddress:      ipaddress,
		Status:         &status,
		ServiceName:    ServiceName,
		ServiceVersion: ServiceVersion,
		Port:           port,
		PropertyNumber: propertynumber,
	}

	err := global.GORM.Create(&service).Error
	if err != nil {
		return err
	} else {
		return nil
	}
}

func (r *servicesInfo) List() (*models.ListReq, error) {
	property := []*models.Service{}
	tx := global.GORM.Model(&models.Service{}).Find(&property)
	if tx.Error != nil {
		return nil, tx.Error
	} else if tx.RowsAffected == 0 {
		return nil, errors.New("占无数据")
	} else {

		return &models.ListReq{
			Items: property,
			Total: len(property),
		}, nil
	}
}

func (r *servicesInfo) Delete(propertynumber string) error {
	err := global.GORM.Where("property_number = ?", propertynumber).Delete(&models.Service{}).Error
	if err != nil {
		return err
	} else {
		return nil
	}
}

func (r *servicesInfo) UpdateService(property_number, username, password, authkey, ipaddress, ServiceName, ServiceVersion string, status, port int) error {
	fmt.Println("status: ", status)
	err := global.GORM.Model(&models.Service{}).Where("property_number=?", property_number).Updates(models.Service{
		Username:       username,
		Password:       password,
		ServiceName:    ServiceName,
		ServiceVersion: ServiceVersion,
		Port:           port,
		IPAddress:      ipaddress,
		AuthKey:        authkey,
		Status:         &status,
	}).Error
	if err != nil {
		return err
	} else {
		return nil
	}
}
